package com.ayoka.parenting.ui.meditation.detail;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.SeekBar;

import com.ayoka.parenting.R;
import com.ayoka.parenting.bean.MeditationBean;
import com.ayoka.parenting.bean.MeditationDetailBean;
import com.ayoka.parenting.databinding.FragmentMeditationDetailAudioTypeBinding;
import com.ayoka.parenting.databinding.FragmentMeditationDetailVideoTypeBinding;
import com.ayoka.parenting.interf.SimpleSeekBarChangeListener;
import com.ayoka.parenting.mvp.BasePresenter;
import com.ayoka.parenting.mvp.BaseView;
import com.ayoka.parenting.mvp.MVPBaseFragment;
import com.ayoka.parenting.service.BackgroundMusicService;
import com.ayoka.parenting.ui.meditation.question.MeditationQuestionActivity;
import com.ayoka.parenting.utils.AudioManagerEvent;
import com.ayoka.parenting.utils.MediaManager;
import com.jincp.common.utils.DateUtil;
import com.jincp.common.utils.MyLogger;
import com.jincp.common.utils.SharedPreferenceUtil;
import com.jzvd.JZMediaIjkplayer;

import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import cn.jzvd.JZVideoPlayer;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: MeditationActivity.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class MeditationDetailAudioTypeFragment extends MVPBaseFragment<FragmentMeditationDetailAudioTypeBinding, MeditationDetailContract.View, MeditationDetailPresenter> implements MeditationDetailContract.View, Observer {

    public static MeditationDetailAudioTypeFragment newInstance(MeditationDetailBean meditationDetailBean) {
        MeditationDetailAudioTypeFragment fragment = new MeditationDetailAudioTypeFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("MeditationDetailBean", meditationDetailBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    private MeditationDetailBean meditationDetailBean;

    private BackgroundMusicService backgroundMusicService;
    private BackgroundMusicConnection servicesConnection;

    private AnimatorSet animatorSet;

    private String meditationAudioUrl, backgroundMusicUrl;

    private boolean updateCompletedStatus;
    private int duration, progress, playingDuration;

    @Override
    protected void configBundleArguments() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            meditationDetailBean = (MeditationDetailBean) bundle.getSerializable("MeditationDetailBean");
        }
    }

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_meditation_detail_audio_type;
    }

    @Override
    protected void initViews(View view) {
        mDataBinding.sbProgress.setOnSeekBarChangeListener(new SimpleSeekBarChangeListener(){

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                MediaManager.getInstance().deleteObserver(MeditationDetailAudioTypeFragment.this);
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mDataBinding.tvCurrentTime.setText(DateUtil.formatTime(progress/ 1000));
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                MediaManager.getInstance().addObserver(MeditationDetailAudioTypeFragment.this);
                MediaManager.getInstance().seekTo(seekBar.getProgress());
            }

        });
        mDataBinding.ivSetting.setOnClickListener(this);
        mDataBinding.ivHt.setOnClickListener(this);
        mDataBinding.ivOperator.setOnClickListener(this);
        mDataBinding.ivQj.setOnClickListener(this);
        mDataBinding.ivStop.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        configMeditationDetailData(meditationDetailBean);
        // 初始化动画
        initAnimatorSet();
        // 初始化背景音乐服务
        initBackgroundMusicService();
        // 获取背景音乐和冥想音乐
        initBackgroundMusicAndMeditationAudioData();
        // 设置监听
        MediaManager.getInstance().addObserver(this);
        AudioManagerEvent.getInstance().addObserver(this);
        AudioManagerEvent.getInstance().requestAudioFocus();
    }

    @Override
    protected MeditationDetailPresenter getPresenter() {
        return new MeditationDetailPresenter();
    }

    @Override
    public void onClick(View view) {
        if (view == mDataBinding.ivSetting) {
            if (mPresenter != null) {
                mPresenter.showMeditationSettingDialog(getChildFragmentManager(), meditationDetailBean);
                mDataBinding.ivSetting.setEnabled(false);
            }
        } else if (view == mDataBinding.ivHt) {
            back(mDataBinding.sbProgress.getProgress());
        } else if (view == mDataBinding.ivQj) {
            forward(mDataBinding.sbProgress.getProgress(), mDataBinding.sbProgress.getMax());
        } else if (view == mDataBinding.ivOperator) {
            onPlayClick(view);
        } else if (view == mDataBinding.ivStop) {

        }
    }

    @Override
    public void configMeditationDetailData(MeditationDetailBean data) {
        if (meditationDetailBean == null || meditationDetailBean.meditation == null) return;
        mDataBinding.tvMeditationTitle.setText(meditationDetailBean.meditation.Title);
        mDataBinding.tvMeditationTitle.setText(meditationDetailBean.meditation.Title);
    }

    @Override
    public void onDialogDismiss(DialogFragment dialog) {
        mDataBinding.ivSetting.setEnabled(true);
    }

    @Override
    public void onSelectedMeditationAudio(MeditationBean.MeditationVoiceBean value) {
        this.meditationAudioUrl = value.MediaUrl;
        MediaManager.getInstance().setMediaDataSource(meditationAudioUrl);
    }

    @Override
    public void onSelectedMeditationBackgroundMusic(MeditationDetailBean.BgMusicsBean value) {
        this.backgroundMusicUrl = value.MediaUrl;
        if (backgroundMusicService != null) {
            backgroundMusicService.startPlay(backgroundMusicUrl);
        }
    }

    @Override
    public void onChangeMeditationBackgroundVolume(float value) {
        if (backgroundMusicService != null) {
            backgroundMusicService.setVolume(value);
        }
    }

    @Override
    public void onUpdateCompletedStatusCallback(boolean isSuccess) {
        this.updateCompletedStatus = isSuccess;
    }

    // 后退
    private void back(int progress) {
        int seekTo = progress - (15 * 1000);
        if (seekTo < 0) {
            MediaManager.getInstance().seekTo(0);
        } else {
            MediaManager.getInstance().seekTo(seekTo);
        }
    }

    // 前进
    private void forward(int progress, int max) {
        int seekTo = progress + (15 * 1000);
        if (seekTo > max) {
            MediaManager.getInstance().seekTo(max);
        } else {
            MediaManager.getInstance().seekTo(seekTo);
        }
    }

    private void onPlayClick(View view) {
        if (MediaManager.getInstance().getPlayStatus() == MediaManager.PLAY) {
            MediaManager.getInstance().pause();
        } else if (MediaManager.getInstance().getPlayStatus() == MediaManager.STOP) {
            MediaManager.getInstance().start();
        } else if (MediaManager.getInstance().getPlayStatus() == MediaManager.RELEASE) {
            MediaManager.getInstance().setMediaDataSource(meditationAudioUrl);
//            MediaManager.getInstance().setMediaDataSource(getActivity(), "http://music.163.com/song/media/outer/url?id=281951.mp3");
            mDataBinding.ivOperator.setOnClickListener(null);
            mDataBinding.progressLoading.setVisibility(View.VISIBLE);

        }
    }

    private void initAnimatorSet() {
        animatorSet = new AnimatorSet();  //组合动画
        ObjectAnimator ringScaleX = ObjectAnimator.ofFloat(mDataBinding.ivBreathe, "scaleX", 1f, 1.1f);
        ObjectAnimator ringScaleY = ObjectAnimator.ofFloat(mDataBinding.ivBreathe, "scaleY", 1f, 1.1f);
        ObjectAnimator circleScaleX = ObjectAnimator.ofFloat(mDataBinding.tvName, "scaleX", 1f, 1.1f);
        ObjectAnimator circleScaleY = ObjectAnimator.ofFloat(mDataBinding.tvName, "scaleY", 1f, 1.1f);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(mDataBinding.ivBreathe, "rotation", 0f, 360f);
        ringScaleX.setRepeatMode(ValueAnimator.REVERSE);
        ringScaleX.setRepeatCount(ValueAnimator.INFINITE);
        ringScaleX.setDuration(4000);
        ringScaleY.setRepeatMode(ValueAnimator.REVERSE);
        ringScaleY.setRepeatCount(ValueAnimator.INFINITE);
        ringScaleY.setDuration(4000);
        circleScaleX.setRepeatMode(ValueAnimator.REVERSE);
        circleScaleX.setRepeatCount(ValueAnimator.INFINITE);
        circleScaleX.setDuration(4000);
        circleScaleY.setRepeatMode(ValueAnimator.REVERSE);
        circleScaleY.setRepeatCount(ValueAnimator.INFINITE);
        circleScaleY.setDuration(4000);
        circleScaleX.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                Log.d(TAG, "onAnimationStart");
                mDataBinding.tvName.setText("Breathe Out");
                mDataBinding.tvName.setTag(true);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                Log.d(TAG, "onAnimationEnd");
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                Log.d(TAG, "onAnimationCancel");
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                Log.d(TAG, "onAnimationRepeat");
                boolean tag = (boolean) mDataBinding.tvName.getTag();
                mDataBinding.tvName.setText(tag ? "Breathe In" : "Breathe Out");
                mDataBinding.tvName.setTag(!tag);
            }
        });
        rotation.setRepeatMode(ValueAnimator.RESTART);
        rotation.setRepeatCount(ValueAnimator.INFINITE);
        rotation.setInterpolator(new LinearInterpolator());
        rotation.setDuration(16000);  //动画时间
        animatorSet.play(ringScaleX).with(ringScaleY).with(circleScaleX).with(circleScaleY).with(rotation);  //同时执行
    }

    private void initBackgroundMusicService() {
        servicesConnection = new BackgroundMusicConnection();
        Intent backgroundMusicIntent = new Intent(getActivity(), BackgroundMusicService.class);
        getActivity().bindService(backgroundMusicIntent, servicesConnection, Service.BIND_AUTO_CREATE);
    }


    private void initBackgroundMusicAndMeditationAudioData() {
        int meditationAudioIndex = SharedPreferenceUtil.getInt("MeditationAudioIndex", 0);
        int backgroundMusicIndex = SharedPreferenceUtil.getInt("BackgroundMusicIndex", 0);
        if (meditationDetailBean != null && meditationDetailBean.meditation != null && meditationDetailBean.meditation.MeditationVoices != null && !meditationDetailBean.meditation.MeditationVoices.isEmpty()) {
            if (meditationAudioIndex >= meditationDetailBean.meditation.MeditationVoices.size()) {
                meditationAudioIndex = 0;
            }
            MeditationBean.MeditationVoiceBean meditationVoiceBean = meditationDetailBean.meditation.MeditationVoices.get(meditationAudioIndex);
            if (meditationVoiceBean != null) {
                meditationVoiceBean.isSelected = true;
                meditationAudioUrl = meditationVoiceBean.MediaUrl;
            }
        }
        if (meditationDetailBean != null && meditationDetailBean.bg_musics != null && !meditationDetailBean.bg_musics.isEmpty()) {
            if (backgroundMusicIndex >= meditationDetailBean.bg_musics.size()) {
                backgroundMusicIndex = 0;
            }
            MeditationDetailBean.BgMusicsBean bgMusicsBean = meditationDetailBean.bg_musics.get(backgroundMusicIndex);
            if (bgMusicsBean != null) {
                bgMusicsBean.isSelected = true;
                backgroundMusicUrl = bgMusicsBean.MediaUrl;
            }
        }
    }

    @Override
    public void update(Observable observer, Object object) {
        if (observer instanceof AudioManagerEvent) {
            int focusChange = (int) object;
            if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                //获得焦点之后的操作
                MediaManager.getInstance().start();
            } else {
                //失去焦点之后的操作
                MediaManager.getInstance().pause();
            }
        }
        if (observer instanceof MediaManager) {
            MediaManager.OperatorResultBean operatorResultBean = (MediaManager.OperatorResultBean) object;
            // 获取时长
            if (operatorResultBean.operation == MediaManager.OperatorResultBean.GET_MEDIA_DURATION) {
                duration = (int) operatorResultBean.operatorValue;
                mDataBinding.sbProgress.setMax(duration);
                mDataBinding.tvTotalTime.setText(DateUtil.formatTime(duration / 1000));
                mDataBinding.progressLoading.setVisibility(View.GONE);
                mDataBinding.ivOperator.setOnClickListener(this);
                MediaManager.getInstance().start();
                if (backgroundMusicService != null) {
                    backgroundMusicService.startPlay(backgroundMusicUrl);
                }
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_PROGRESS_UPDATE) {// 更新播放进度
                playingDuration += 250;
                progress = (int) operatorResultBean.operatorValue;
                mDataBinding.sbProgress.setProgress(progress);
                mDataBinding.tvCurrentTime.setText(DateUtil.formatTime(progress / 1000));
                if (duration - progress <= 10 * 1000 && !updateCompletedStatus){
                    this.updateCompletedStatus = true;
                    mPresenter.updateCompletedStatus(meditationDetailBean.record_id, playingDuration / 1000);
                }
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_UPDATE) {// 更新缓冲进度
                int progress = (int) operatorResultBean.operatorValue;
                mDataBinding.sbProgress.setSecondaryProgress(progress * duration);
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_START) {// 开始播放
                mDataBinding.ivOperator.setImageResource(R.mipmap.icon_meditation_pause);
                if (backgroundMusicService != null) {
                    backgroundMusicService.start();
                }
                if (animatorSet != null) {
                    animatorSet.start();
                }
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_STOP) {// 停止播放
                mDataBinding.ivOperator.setImageResource(R.mipmap.icon_meditation_play);
                if (backgroundMusicService != null) {
                    backgroundMusicService.pause();
                }
                if (animatorSet != null) {
                    animatorSet.cancel();
                }
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_MEDIA_PLAYER_COMPLETION) {// 播放完成
                mDataBinding.ivOperator.setImageResource(R.mipmap.icon_meditation_play);
                if (backgroundMusicService != null) {
                    backgroundMusicService.stop();
                }
                if (animatorSet != null) {
                    animatorSet.cancel();
                }
                Activity activity = getActivity();
                if (activity != null && !activity.isFinishing()) {
                    MeditationQuestionActivity.start(activity, meditationDetailBean.record_id);
                    activity.finish();
                }
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_START) {// 开始缓冲
                mDataBinding.progressLoading.setVisibility(View.VISIBLE);
            } else if (operatorResultBean.operation == MediaManager.OperatorResultBean.ON_BUFFERING_END) {// 结束缓冲
                mDataBinding.progressLoading.setVisibility(View.GONE);
            }
        }
    }

    private class BackgroundMusicConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            if (service instanceof BackgroundMusicService.BackgroundMusicBinder) {
                BackgroundMusicService.BackgroundMusicBinder binder = (BackgroundMusicService.BackgroundMusicBinder) service;
                backgroundMusicService = binder.getService();
            }
        }

        //client 和service连接意外丢失时，会调用该方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    public void onDestroy() {
        MediaManager.getInstance().release();
        MediaManager.getInstance().deleteObserver(this);
        AudioManagerEvent.getInstance().deleteObserver(this);
        AudioManagerEvent.getInstance().abandonAudioFocus();
        if (getActivity() != null && servicesConnection != null && backgroundMusicService != null) {
            backgroundMusicService.release();
            Intent backgroundMusicIntent = new Intent(getActivity(), BackgroundMusicService.class);
            getActivity().stopService(backgroundMusicIntent);
            getActivity().unbindService(servicesConnection);
        }
        super.onDestroy();
    }
}
